package com.example.p2pshare.component;

import com.example.p2pshare.utils.SampleRepository;
import io.ep2p.kademlia.NodeSettings;
import io.ep2p.kademlia.exception.UnsupportedBoundingException;
import io.ep2p.kademlia.netty.NettyKademliaDHTNode;
import io.ep2p.kademlia.netty.builder.NettyKademliaDHTNodeBuilder;
import io.ep2p.kademlia.netty.common.NettyConnectionInfo;
import io.ep2p.kademlia.node.KeyHashGenerator;
import io.ep2p.kademlia.util.BoundedHashUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

@Component
public class NodeStart implements CommandLineRunner {

    @Value("${bootstrap.ip}")
    private String bootstrapIp;


    @Value("${bootstrap.port}")
    private int bootstrapPort;


    private NettyKademliaDHTNode<String, String> node1;

    public void startNode() {
        KeyHashGenerator<BigInteger, String> keyHashGenerator = key -> {
            try {
                return new BoundedHashUtil(NodeSettings.Default.IDENTIFIER_SIZE).hash(key.hashCode(), BigInteger.class);
            } catch (UnsupportedBoundingException e) {
                e.printStackTrace();
            }
            return BigInteger.valueOf(key.hashCode());
        };

        node1 = new NettyKademliaDHTNodeBuilder<>(
                BigInteger.valueOf(1L),
                new NettyConnectionInfo(bootstrapIp, bootstrapPort),
                new SampleRepository(),
                keyHashGenerator,
                String.class, String.class).build();
        node1.start();

        System.out.println("引导节点:节点1启动");
    }


    public NettyKademliaDHTNode<String, String> getNode() {
        return node1;
    }


    @Override
    public void run(String... args) throws Exception {
        startNode();
    }
}
